﻿@page "/product"

@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject IProductService ProductService
@inject IProductCategoryService ProductCategoryService

<RadzenText TextStyle="TextStyle.H4">商品管理</RadzenText>
<PageTitle>商品管理</PageTitle>
<RadzenStack Style="display:flex;" Orientation="Orientation.Horizontal">

    <RadzenTree Style="height: 88vh;width: 20%; margin: 10px 0px 10px 10px;" @bind-Value=@SelectedNode Data=@Tree Change=OnTreeChange>
        <RadzenTreeLevel TextProperty="Name"
        ChildrenProperty="Children"
        Expanded=@ShouldExpand
        HasChildren=@(e => (e as ProductCategoryDto)!.Children.Any()) />
    </RadzenTree>

    <RadzenStack Style="flex:1; width: 80%; height:83vh;" Orientation="Orientation.Vertical">
        <RadzenStack Style="display:flex" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Start">
            <RadzenTextBox @bind-Value="@keyword" Placeholder="名称" Style="margin:10px 0px 10px 0px" />
            <RadzenButton Icon="refresh" Click=@(args => Search()) ButtonStyle="ButtonStyle.Primary" Style="margin:10px 0px 10px 0px" />
            <RadzenButton Icon="add_circle" Click=@(args => Add()) ButtonStyle="ButtonStyle.Primary" Style="margin:10px 0px 10px 0px" />
        </RadzenStack>

        <RadzenDataGrid EmptyText="暂无数据" 
                        Style="flex:1;height:80vh;"
                        TItem="ProductDto" 
                        Data="@products" 
                        GridLines="Radzen.DataGridGridLines.Default" 
                        AllowPaging="true" 
                        AllowSorting="true">
            <Columns>
                <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                <RadzenDataGridColumn Property="" Title="操作" Width="260px">
                    <Template Context="data">
                        <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                            <RadzenButton Icon="edit" @onclick:stopPropagation Click="@(args=> Update(data))" ButtonStyle="ButtonStyle.Primary" />
                            <RadzenButton Icon="delete" @onclick:stopPropagation Click="@(args=> Delete(data))" ButtonStyle="ButtonStyle.Danger" />
                        </RadzenStack>
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="Code" Title="代码" />
                <RadzenDataGridColumn Property="Name" Title="名称" />
                <RadzenDataGridColumn Property="Unit" Title="单位" />
                <RadzenDataGridColumn Property="Remark" Title="备注" />
            </Columns>
        </RadzenDataGrid>
    </RadzenStack>
</RadzenStack>

@code {

    // 搜索关键字
    string keyword = string.Empty;

    // 产品列表
    ObservableCollection<ProductDto> products = default!;

    // 产品类型树
    List<ProductCategoryDto> Tree { get; set; } = default!;

    // 选中的产品类型节点
    object? SelectedNode;

    // 是否展开
    bool ShouldExpand(object data)
    {
        return true;
    }

    // 选中的产品类型节点
    private async Task OnTreeChange(object value)
    {
        var args = value as Radzen.TreeEventArgs;
        var category = (ProductCategoryDto) args!.Value;
        SelectedNode = category;
        if (category != null)
        {
            await LoadProducts(category.Id);
        }
    }

    // 加载产品列表
    async Task LoadProducts(long categoryId)
    {
        var list = await ProductService.Search();

        // 根据产品分类ID筛选产品(选中根节点)
        if(categoryId == 1)
        {
            products = new ObservableCollection<ProductDto>(list);
            return;
        };

        // 根据产品分类ID筛选产品(选中子节点)
        var children = list.Where(s => s.ProductCategoryId == categoryId);
        products = new ObservableCollection<ProductDto>(children);
    }

    // 搜索产品
    async Task Search()
    {
        if (SelectedNode == null)
        {
            await DialogService.Alert("请先选择产品分类", "提示", new AlertOptions() { OkButtonText = "确定" });
            return;
        }
        var list = await ProductService.Search(keyword);
        var categoryId = ((ProductCategoryDto)SelectedNode).Id;
        if (categoryId == 1)
        {
            products = new ObservableCollection<ProductDto>(list);
            return;
        }
        var children = list.Where(s => s.ProductCategoryId == ((ProductCategoryDto)SelectedNode).Id);
        products = new ObservableCollection<ProductDto>(children);
    }

    private async Task Add()
    {
        if (SelectedNode == null)
        {
            await DialogService.Alert("请先选择产品分类", "提示", new AlertOptions() { OkButtonText = "确定" });
            return;
        }
        var categoryDto = SelectedNode as ProductCategoryDto;
        var categoryId = categoryDto!.Id;
        if (categoryId == 1)
        {
            await DialogService.Alert("产品不能直接添加到根节点下", "提示", new AlertOptions() { OkButtonText = "确定" });
            return;
        }

        var productCategory = ProductCategoryService.GetTree();
        var newProduct = new ProductDto()
            {
                ProductCategoryId = categoryDto.Id,
            };

        ProductDto result = await DialogService.OpenAsync<ProductAddDialog>($"新增产品",
               new Dictionary<string, object>() {{ "PProduct", newProduct }},
               new DialogOptions()
                   {
                       Resizable = true,
                       Draggable = true,
                       Width = "700px",
                       Height = "512px",
                       Left = null,
                       Top = null
                   });
        
        if (result != null)
        {
            try
            {
                products!.Add(result);
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }

    private async Task Update(ProductDto selectedItem)
    {
        ProductDto result = await DialogService.OpenAsync<ProductAddDialog>($"修改产品",
                      new Dictionary<string, object>() { { "PProduct", selectedItem } },
                      new DialogOptions()
                          {
                              Resizable = true,
                              Draggable = true,
                              Width = "700px",
                              Height = "512px",
                              Left = null,
                              Top = null
                          });
        if (result != null)
        {
            StateHasChanged();
        }
    }

    private async Task Delete(ProductDto selectedItem)
    {
        var result = await DialogService.Confirm("确认要删除吗?", "提示", new ConfirmOptions()
            {
                OkButtonText = "确定",
                CancelButtonText = "取消"
            });

        if ((bool)result)
        {
            try
            {
                await ProductService.Delete(selectedItem.Id);
                products.Remove(selectedItem);
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
       Tree = await ProductCategoryService.GetTree();
       SelectedNode = Tree?.FirstOrDefault();
    }

}

